开发者

Javascript validation -Which one is best (Name or ID )

I have two option of JavaScript validation .Among these which one better to use for validation

Javascript validation based on FIELD NAME

if(document.formname.uname.value=="")
{
alert("Please Enter Username");
document.formname.uname.focus();
return false;
}

Javascript validation based on ID

if(document.getElementById('uname').value=="")
{
alert("Please Enter Username");
document.getElementById('uname'开发者_JAVA百科).focus();
return false;   
}


Avoid using ids, but don't access forms that way.

Here are a couple of general rules of thumb:

Get a reference to the form and use that

Don't use globals. This makes code more reusable.

e.g.

function submitHandler (e) {
    var myForm = this;
}
document.getElementById('myForm').addEventListener('submit', submitHandler);

Note that addEventListener, while standard, isn't supported by older versions of IE. Use a library to abstract your event binding.

Once you have a reference, use the elements collection

myForm.elements.control …

Where control can be a name or an id. If it is a name and you have multiple controls with the same name (e.g. a checkbox group), then it will return a NodeList you can iterate over.


In my opinion the first option with document.fromname.uname is better. Using IDs is like a globale variable. It is better to use the namespace of the form to avoid conflicts.

Also you only have to set the name attribute of the input field instead of name and id.


It just depends on how you want to select items in the form. ID is always to be unique for each element whereas name doesn't have to be. So using name, you can select multiple elements quite simply, especially usefull for forms created using javascript with an unknown number of fields.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜