我有一個有五個字段的表單; first name
,last name
,username
,password
和passwordConfirmation
。使用javascript驗證表單的正確方法(簡單)
我首先想說的是,我不想要最複雜的方法,這是一個非常簡單的網站,永遠不會上線,它純粹是爲了演示目的,我不擔心錯誤捕捉在有害的用戶輸入意義上。
到目前爲止,我有這樣的:
function validateRegistrationForm(firstName, lastName, username, password, passwordConfirmation) {
alert("validate form function has been called");
//alert("function has been called");
//---
var firstName = firstName;
//alert(firstName);
var lastName = lastName;
//alert(lastName);
var username = username;
//alert(username);
var password = password;
//alert(password);
var passwordConfirmation = passwordConfirmation;
//alert(passwordConfirmation);
//---
//**The code that I have sectioned off here, I am unsure whether I need it or not, could someone please explain to me why I would do this, and not just reference the parameters in the function directly?**
// Check here if all the fields in the registeration form have been filled.
if (firstname == null || firstname == "") {
//firstname hasn't been filled out
}
if (lastName == null || lastName == "") {
//lastname hasn't been filled out
}
if (username == null || username == "") {
//username hasn't been filled out
}
if (password == null || password == "") {
//password hasn't been filled out
}
if (passwordConfirmation == null || passwordConfirmation == "") {
//passwordconfirmation hasn't been filled out
}
}
我想有一個方法來檢查,如果每個字段已經填寫了(我在這裏,我認爲)的,如果沒有,產生例如圍繞所述輸入元素的紅色邊框的通知和/或具有關於如何解決問題的指示的消息。我知道這可以用CSS來完成,但我不確定最有效的方法。
目前我已經創建了這兩個功能:
function generateError(messageText, elementIdentifier) {
alert("error generator called");
//var element = document.getElementById(elementID);
//var error = document.createTextNode(message);
//element.innerHTML = message;
alert("Element: " + elementIdentifier + ", Reason: " + messageText);
}
function validatePassword(password, passwordConfirmation) {
alert("password check called");
if (password == passwordConfirmation) {
if (password.length < 8) {
//password too short
//alert("password\'s match but they are too short");
return false;
} else {
//passwords match and the right length
//alert("password\'s match and they are 8 characters or longer");
return true;
}
} else {
//the two do not match
//alert("they don\'t match")
generateError("Passwords don\'t match", "password");
return false;
}
}
的validatePassword()
函數採用密碼和確認密碼兩個參數,我想這樣的作品已經,我要的是用於傳遞生成的錯誤到generateError()
函數將它們全部存儲在一個數組中,然後逐個遍歷它們向用戶顯示出什麼是錯誤的。
我固定一個';'和'失蹤)'但我不得不爲了達到6個字符編輯的要求插入一些虛擬的空間字符。 –
我不得不改變功能'setClass'所解釋[這裏](http://stackoverflow.com/questions/2155737/remove-css-class-from-element-with-javascript-no-jquery),因爲該功能' document.getElementById(id).removeClass()'和'document.getElementById(id).addClass()'不工作(可能是他們jQuery?),Chromium報告的錯誤是'TypeError:'undefined'一個功能'。 –
方法'.innerText'不Firefox支持的,最好是使用'.innerHTML' –