JavaScript form verification (1): javascript Form Verification
The submit button is required for default submission.
To submit a normal button, you must call the submit method of the form.
Form Verification is to prompt and re-enter an invalid element,
And cancel the form submission.
(In fact, it is the operation on strings and regular expressions)
Focus () Get focus
Select () select All
<Html>
<Head>
<Title> damel14 </title>
<Script>
Function checkName (){
Var usernameObj = document. forms [0]. username;
Var username = usernameObj. value;
// Var username = document. forms [0]. username. value;
If (username = "" | username. length <1 ){
Alert ("user name cannot be blank ");
UsernameObj. focus ();
UsernameObj. select ();
Return false;
}
If (username. length <5 | username. length> 10 ){
Alert ("the user name length must be between 5-10 ");
UsernameObj. focus ();
UsernameObj. select ();
Return false;
}
Var t = true;
For (var I = 0; I <username. length; I ++ ){
Var c = username. toLowerCase (). charAt (I );
If (! (C> 'A' & c <= 'Z') | (c> '0' & c <'9 ') | (c = '_')))
T = false;
}
If (t = false ){
Alert ("the user name can only contain numbers, letters, and underscores ");
Return false;
}
Return true;
}
Function checkPass (){
Var passObj = document. forms [0]. password; // get the object
Var pass = passObj. value;
// Var pass = document. forms [0]. password. value;
If (pass. length = "" | pass. length <1 ){
Alert ("the password cannot be blank ");
PassObj. focus (); // get the object focus
PassObj. select (); // select object
Return false;
}
If (pass. length <6 | pass. length> 16 ){
Alert ("the password length must be between 6 and 16 ");
PassObj. focus ();
PassObj. select ();
Return false;
}
Return true;
}
Function checkForm (){
Return checkName () & checkPass ();
}
</Script>
</Head>
<Body>
<Form action = "damel11.html" onSubmit = "return checkForm ()" name = "myform">
Username: <input type = "text" name = "username"/>
</Br>
Password & nbsp; Code: <input type = "text" name = "password" onClick = "checkName ()"/>
</Br>
<Input type = "submit" value = "OK"/>
</Form>
</Body>
<Html>
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.