html form validation,html - JavaScript - Form Validation - Stack Overflow

东门晓博
2023-12-01

As Kevmo mentioned a library, here is a quick and dirty example using jquery. Once you have the basics of javascript mastered look into jQuery, it will make your life a lot easier.

HTML not the absence on any calls to javascript functions and our required fields have the required class

Family name

Family Name Required

First name

First Name required

Dogs' name

CSS Just some basics

.requiredText {

display:none;

color:#F00;

}

label {

display:inline-block;

width:20%;

}

.required {

border-color:#F33;

}

input {

width:60%;

border:solid 1px #CCC;

margin-top:5px;

}

Javascript

I've used the following from jquery:

$(document).ready(function () { /* Execute when DOM is loaded */

/*Assign blur event handler to fields with required class */

/*I have used the id of the form (#formToValidate) to scope the selctor.

Not required but a good practice*/

$("#formToValidate .required").blur(function () {

if ($(this).val() === "") { /*Check the value of the item being blured"*/

$(this).next(".requiredText").slideDown('fast'); /* Slide down the nearest alert text sibling*/

} else {

$(this).next(".requiredText").slideUp('fast'); /* Slide up the nearest alert text sibling*/

}

});

});

 类似资料: