js form filling checking
How could i return user to unfilled field when he push "submit" button?
I have something like this:
<!--Contact Name-->
<div class="section" id="inputdiv">
<span class="fieldname">Name:</span>
<input type="text" id="contactname" /> <!-- Nessesary to be filled-->
<script type="text/javascript">
var contactname = new LiveValidation('contactname');
contactname.add(Validate开发者_StackOverflow社区.Presence);
</script>
</div>
<a class="button-more" style="width:903px; float: right; font-size: 15px; margin-top: 15px;" href="">Submit my answers</a>
Or just this:
<input type="text" id="contactname" /> <!-- Nessesary to be filled-->
<a href="">Submit my answers</a>
You should execute the following code while the user clicks "Submit":
if (document.getElementById('contactname').value=='') document.getElementById('contactname').focus();
else // if the field isn't empty, proceed
EDIT: Oh, I'm sorry, I've just noticed the "jquery" tag. Does it have to be created in jQuery? I don't know jQuery, but you may use the above code as well ;)
And remember, you should also check all the fields on the server's side as some experienced user may easily manipulate the client-side code.
Ideally, if you want to allow people who are not running javascript in their browsers to use your form, you should be using a <input type="submit" />
button followed by server-side validation, with javascript validation as a shortcut for those users who are running it.
To add javascript validation, you can either attach some javascript to the form's submit event, or to the click event of an anchor:
<form name="example" action="example.asp" method="post" onsubmit="javascript:return validate(this) ;">
<input type="text" name="contactname" id="contactname" />
<input type="submit" name="submit" value="Button-Label" />
</form>
<script type="text/javascript">
function validate(frm) {
var message = '' ;
if(frm.contactname.length < 1) {
// Put cursor in field.
if(message.length < 1) frm.contactname.focus() ;
message = message + 'Please enter your name.\n' ;
}
if(message.length > 0) {
alert(message) ;
// Stop the form submitting
return false ;
}
return true ;
}
</script>
Form validation shouldn't happen only in the front with HTML and JS since it's too easy to bypass. You should also do some checks in your backend.
That being said, you'll need to actually have a form in order to check correctly its validity. For instance:
<form id="abcd">
<input id="input" />
</form>
then
$("abcd").submit(function(e){
return ( $("#input").val() != "" );
});
I used jQuery syntax, but it's basically the same thing with normal JS.
If you could also use all the nice plugins out there like http://bassistance.de/jquery-plugins/jquery-plugin-validation/
If you don't want a form, just do a test on click on the submit link and test the value here.
精彩评论