validating form javascript - javascript

i have a form with the following validation rules:
<script type="text/javascript">
var errmsg;
function validate()
{
var textA= document.getElementById("text1");
var textC = document.getElementById("text3");
var txt1 = document.getElementById("text1").value;
var txt3 = document.getElementById("text3").value;
var txt1_len = txt1.length;
var txt3_len = txt3.length;
if(txt1_len == 0 || txt1_len > 50 || txt1_len < 10)
{
errmsg = "Error .";
document.getElementById("ermsg").innerHTML = errmsg;
textA.focus();
return false;
}
else if(txt3_len == 0 || txt3_len > 30 || txt3_len < 10)
{
errmsg = "Invalid password!";
document.getElementById("ermsg").innerHTML = errmsg;
textC.focus();
return false;
}
else
{
return true;
}
return false;
}
</script>
these rules should alert the user if he enters less than 10 characters in the first field. I would like to know if i can alert the user as well if he doesn't enters some characters in that field.
For example if the user enters mynamehere i want him to enter my-name-here and also to restrict users to enter the email address in that field.
how can i achieve that using those rules?
thanks

I have taken your snippet and edit it :
var errmsg;
function validate() {
var textA = document.getElementById("text1");
var textC = document.getElementById("text3");
var txt1 = document.getElementById("text1").value;
var txt3 = document.getElementById("text3").value;
var txt1_len = txt1.length;
var txt3_len = txt3.length;
var $err = document.getElementById("ermsg");
$err.innerHTML = "Everything is ok!";
$err.style.color = "black";
if (txt1_len == 0 || txt1_len > 50 || txt1_len < 10 || !/.+-.+-/.test(txt1)) {
errmsg = "Error .";
$err.innerHTML = errmsg;
$err.style.color = "red";
textA.focus();
return false;
} else if (txt3_len == 0 || txt3_len > 30 || txt3_len < 10 || !validateEmail(txt3)) {
errmsg = "Invalid password!";
$err.innerHTML = errmsg;
$err.style.color = "red";
textC.focus();
return false;
} else {
return true;
}
return false;
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
<input type="text" id="text1" />
<input type="text" id="text3" />
<button onclick="return validate();">Validate</button>
<p>
<div id="ermsg"></div>
</p>
The test are at the end of the condition on txt1 and txt3 :
!/.+-.+-/.test(txt1)
and
!validateEmail(txt3)
EDIT :
The rule on field text1 seems to be : text should contains only numbers / letters / minus sign.
So you can change the rule with :
/^[a-z0-9\-]+$/i.test(txt1)
There are many RegExp tutorials on the web, for example :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Related

Javascript is partially working and isn't returning an answer

My javascript code is partially working, it works on the first name validation, on the Email validation it shows the error for a second but it doesn't return false and the password validation isn't working at all.
function validate() {
var emailOk = validateEmail();
var fNameOk = validateFirstName();
var paswOk = validatePassword();
return fNameOk;
return paswOk;
return emailOk;
}
function validatePassword() {
var name = document.getElementById("psw");
name.style.borderColor = "";
document.getElementById("passwordErr").innerText = "";
if (name.value.length < 7) {
name.style.borderColor = "red";
var error = document.getElementById("passwordErr");
error.innerText = "Password does not fit the criteria.";
return false;
}
else
return true;
}
function validateFirstName() {
var name = document.getElementById("F_Name");
name.style.borderColor = "";
document.getElementById("fNameErr").innerText = "";
if (name.value.length == 0) {
name.style.borderColor = "red";
var error = document.getElementById("fNameErr");
error.innerText = "Missing first name.";
return false;
}
else
return true;
}
function validateEmail() {
var name = document.getElementById("email");
name.style.borderColor = "";
document.getElementById("emailErr").innerText = "";
var re = /\S+#\S+\.\S+/;
if (re.test(name) == true)
return true;
else
var error = document.getElementById("emailErr");
error.innerText = "Not a vaild email.";
return false;
}
I expect it to stop when you enter a password that is shorter than 7 and for it to show the message. I also expect it to stop when The email is invalid.
You are writing your else statements incorrectly. They should also be opened and closed with curly brackets
else { // code }
Also, code written after a return statement will not be executed. You will need to return 3 variables at the same time, using an object or array.
function validate() {
var emailOk = validateEmail();
var fNameOk = validateFirstName();
var paswOk = validatePassword();
console.log(fNameOk, paswOk, emailOk)
return {
fNameOk,
paswOk,
emailOk
}
}
function validatePassword() {
var name = document.getElementById("psw");
name.style.borderColor = "";
document.getElementById("passwordErr").innerText = "";
if (name.value.length < 7) {
name.style.borderColor = "red";
var error = document.getElementById("passwordErr");
error.innerText = "Password does not fit the criteria.";
return false;
} else {
return true;
}
}
function validateFirstName() {
var name = document.getElementById("F_Name");
name.style.borderColor = "";
document.getElementById("fNameErr").innerText = "";
if (name.value.length == 0) {
name.style.borderColor = "red";
var error = document.getElementById("fNameErr");
error.innerText = "Missing first name.";
return false;
} else {
return true;
}
}
function validateEmail() {
var name = document.getElementById("email");
name.style.borderColor = "";
document.getElementById("emailErr").innerText = "";
var re = /\S+#\S+\.\S+/;
if (re.test(name) == true) {
return true;
} else {
var error = document.getElementById("emailErr");
error.innerText = "Not a vaild email.";
return false;
}
}
<input id="email" placeholder="Email" /><br>
<input id="F_Name" placeholder="First Name" /><br>
<input id="psw" type="password" placeholder="Password" /><br>
<button onclick="validate()">Register</button>
<div id="passwordErr"></div>
<div id="fNameErr"></div>
<div id="emailErr"></div>
One thing I can say, use:
return fNameOk && paswOk && emailOk;
instead of:
return fNameOk;
return paswOk;
return emailOk;
Because when you write "return fNameOk;", it will return from the function. The next two lines will never be executed.

Creating a pattern for a number which must be prefixed by 3 letters eg (IKA111111)

function validatetest(e)
{
debugger;
e.preventDefault();
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var title = document.getElementById("title").value;
var healthNumber = document.getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var telephoneNumber = parseInt(document.getElementById("telephoneNumber").value);
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
var validText = /^[a-zA-Z]*$/;
var validLastText = /^[a-zA-Z-]*$/;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
//var n = healthNumber.startsWith("ZHA");
if(firstName!="" && lastName!= "" && title!="" && email !="")
{
if(email.match(validEmail))
{
if(!isNaN(telephoneNumber) && telephoneNumber >= 11111111111 && telephoneNumber <= 99999999999)
{
if(firstName.match(validText) && firstName.length >1)
{
if(lastName.match(validLastText) && lastName.length> 1)
{
if(healthNumber.match(validHealth))
{
alert("All information is Validated");
return true;
}
else
{
alert("error error");
return false;
}
}
else
{
document.getElementById("error4").innerHTML="letters and hypen only";
return false;
}
}
else
{
document.getElementById("error").innerHTML="letters only and more then one character";
return false;
}
}
else
{
document.getElementById("error2").innerHTML="Telephone number must be 11 num digits long";
}
}
else
{
document.getElementById("error3").innerHTML="email is not a valid format ";
return false;
}
}
else
{
alert("All fields must be entered except telephone Number ");
return false;
}
}
i am trying to create a validation process by using a pattern for a user inputted healthnumber so that it validates whether 3 letters are entered followed by 6 numbers via user input. (MIC123456 is example so MIC always has to been entered , those specific letters)
Not sure if my technique is correct by using a pattern stored in the ValidHeath variable as you can i have used this idea for my email validation etc .
You have an extra + in your regex, make it
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
Demo
var isMatch = !!"IKA111111".match(/^[A-Z]{3}[0-9]{6}$/);
isMatch ? console.log( "Matching" ) : console.log( "Not Matching" );

code does not validate email from a form, in javascpricpt

hi i font know if this is the right place to ask this question but i have a problem with my code that i cannot figure out. i have tried many different algorithms and none work. i am trying to validate email from a form.
here is the code (form is in html)
function isValidString(str) {
var quot = "\"";
if (str.indexOf(quot) != -1)
return false;
var badStr = "$%^&*()_+[]{}<>?אבגדהוזחטיכךלמםנןסעפצקרשת";
var i = 0,
p;
while (i < str.length) {
p = badStr.indexOf(str.charAt(i));
if (p != -1)
return false;
i++;
}
return true;
}
function isValidEmail()
{
var str = document.getElementById("email").value;
document.write("email from isValidEmail(str) = " + email);
if (isEmpty(str) || str.length < 5) {
alert("isEmpty(str) || str.length < 5 = false");
return false;
}
if (!isValidString(str)) {
alert("!isValidString(str) = false");
return false;
}
var atSign = str.indexOf('#');
if (atSign == -1 || str.lastIndexOf('#') || atSign === 0 || atSign == str.length - 1) {
alert("atSign == -1 || str.lastIndexOf('#') || atSign == 0 || atSign == str.length - 1 = false");
return false;
}
var dotSign = str.indexOf('.', atSign);
if (dotSign == -1 || dotSign === 0 || dotSign == str.length - 1 || dotSign - atSign < 2) {
alert("dotSign == -1 || dotSign == 0 || dotSign == str.length - 1 || dotSign - atSign < 2 = false");
return false;
}
return true;
no matter what i input it always comes back valid.
here is the part where i apply it:
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
thanks in advance
An example of using the parser library mentioned in my comment.
var eAddr = document.getElementById('eAddr'),
check = document.getElementById('check'),
pre = document.getElementById('out');
check.addEventListener('click', function (evt) {
pre.textContent = !!emailAddresses.parseOneAddress(eAddr.value.trim());
}, false);
<script src="https://rawgit.com/FogCreek/email-addresses/master/lib/email-addresses.js"></script>
<input id="eAddr"></input>
<button id="check">Test pattern</button>
<pre id="out"></pre>
Note: this will accept Goodhertz Inc <support#goodhertz.com> as it stands and you would need to further check the object returned by parseOneAddress to filter these out.
You don't call the rigth function i. e. call
var email = document.getElementById("email").value;
if (isValidString(email)) {
alert("invalid email");
return false;
}
return true;
instead of
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
Using Regular expression is the best method for validating input elements. Below function can validate email perfectly.
function regExValidate_Email(id) {
var email = document.getElementById(id).value;
if (email != '') {
var regExforEmail = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (regExforEmail.test(email)) {
$("#" + id).css("background-color", "#ffffff");
return true;
}
else {
alert('Please enter a valid email id. \nex: yourname#example.com');
document.getElementById(id).style.backgroundColor = '#feffea';
document.getElementById(id).value = '';
Ctrlid = id;
setTimeout("document.getElementById(Ctrlid).focus()", 1);
return false;
}
}
else { document.getElementById(id).style.backgroundColor = 'white'; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Email: <input type="email" onblur="return regExValidate_Email(this.id)" id="txtEmail" />

Can't figure out what's wrong with this if statement?

I'm trying to make a form in which, when the user fills out all fields, the output results in a compilation of all of their entered data. The form connects to a php file and it runs just fine, however when I tried to add validation the submit acts strangely.
Basically my "Validation" is made of multiple if statements with one else. The title and content validation are in perfect working order,but when it comes to the type it submits the form anyway.
Any suggestions?
HTML Code:
<body>
<form id="documentationForm" action="testingPHP2.php" method="post">
<figcaption>
<p><strong>Instructions:</strong>
</p>
<p><i>Fill out the information as needed below. Place each step on a new line. When you are finished,<br>submit the document and download the file.</p></i>
</figcaption>
<strong>Title:</strong>
<input id="docTitle" type="text" name="docTitle"><span id="errorTitle"></span>
<br>
<strong>Type:</strong>
<select id="docType" onchange="adaptiveLabel()" name="docType">
<br>
<option value="" selected>Select Document Type</option>
<option value="Procedure">Procedure</option>
<option value="Instruction">Instruction</option>
<option value="Form">Form</option>
</select><span id="errorType"></span>
<br>
<script>
function adaptiveLabel() {
var chosenType = document.getElementById("docType");
var chosenTypeVal = chosenType.value;
var x = document.getElementById("contentLabel");
if (chosenTypeVal == "Procedure") {
x.innerHTML = "Procedural Steps:";
}
if (chosenTypeVal == "Instruction") {
x.innerHTML = "Steps:"
}
if (chosenTypeVal == "Form") {
x.innerHTML = "Form Parts:";
}
if (chosenTypeVal == " ") {
x.innerHTML = " ";
}
}
function submitInputs() {
var errorTitletext = document.getElementById("docTitle");
var errorTitleLable = document.getElementById("errorTitle");
var errorContenttext = document.getElementById("docInput");
var errorContentLabel = document.getElementById("errorContent");
var errorTypetext = document.getElementById("docType");
var errorTypetextLable = document.getElementById("errorType");
if (errorTypetext.value === "") {
alert("You must select a type");
errorTypetextLable.innerHTML = "*Please select a type";
errorTypetextLable.style.color = "red";
}
if (errorTypetext.value === "Procedure" || errorTypetext.value === "Form" || errorTypetext.value === "Instruction") {
errorTypetextLable.innerHTML = "";
errorTypetextLable.style.color = "";
}
if (errorTitletext.value.length === 0 || errorTitletext.value === " ") {
alert("You must create a title");
errorTitleLable.innerHTML = "*Please create a title";
errorTitleLable.style.color = "red";
}
if (errorTitletext.value.length > 0) {
errorTitleLable.innerHTML = "";
errorTitleLable.style.color = "";
}
if (errorContenttext.value.length === 0) {
alert("You must enter content");
errorContentLabel.innerHTML = "*Please enter content";
errorContentLabel.style.color = "red";
}
if (errorContenttext.value.length > 0) {
errorContentLabel.innerHTML = "";
errorContentLabel.style.color = "";
} else {
document.getElementById("documentationForm").submit();
}
}
</script>
<strong><span id="contentLabel"></span><span id="errorContent"></span></strong>
<br>
<textarea style="width: 500px; height: 250px;" id="docInput" name="docInput"></textarea>
<br>
<input type="button" onclick="submitInputs()" value="Create Document">
<input type="submit" value="Default Submit">
</form>
</body>
You should submit the form only if all the values are valid, so use a flag as given below. Also it will be easier to use if...else construct to handle invalid & valid case of a field.
In you logic the problem is irrespective of the first 2 fields valid state, if the content is valid the form's submit is called.
function submitInputs() {
var errorTitletext = document.getElementById("docTitle");
var errorTitleLable = document.getElementById("errorTitle");
var errorContenttext = document.getElementById("docInput");
var errorContentLabel = document.getElementById("errorContent");
var errorTypetext = document.getElementById("docType");
var errorTypetextLable = document.getElementById("errorType");
var valid = true;
if (errorTypetext.value === "") {
alert("You must select a type");
errorTypetextLable.innerHTML = "*Please select a type";
errorTypetextLable.style.color = "red";
valid = false;
} else {
errorTypetextLable.innerHTML = "";
errorTypetextLable.style.color = "";
}
if (errorTitletext.value.length === 0 || errorTitletext.value === " ") {
alert("You must create a title");
errorTitleLable.innerHTML = "*Please create a title";
errorTitleLable.style.color = "red";
valid = false;
} else {
errorTitleLable.innerHTML = "";
errorTitleLable.style.color = "";
}
if (errorContenttext.value.length === 0) {
alert("You must enter content");
errorContentLabel.innerHTML = "*Please enter content";
errorContentLabel.style.color = "red";
valid = false;
} else {
errorContentLabel.innerHTML = "";
errorContentLabel.style.color = "";
}
if (valid) {
document.getElementById("documentationForm").submit();
}
}
Demo: Fiddle
Also There is no need to have a default submit button, you can have only one button like
<form id="documentationForm" action="testingPHP2.php" method="post" onsubmit="return submitInputs();">
.....
<input type="submit" value="Create Document" />
</form>
then
function submitInputs() {
var errorTitletext = document.getElementById("docTitle");
var errorTitleLable = document.getElementById("errorTitle");
var errorContenttext = document.getElementById("docInput");
var errorContentLabel = document.getElementById("errorContent");
var errorTypetext = document.getElementById("docType");
var errorTypetextLable = document.getElementById("errorType");
var valid = true;
if (errorTypetext.value === "") {
alert("You must select a type");
errorTypetextLable.innerHTML = "*Please select a type";
errorTypetextLable.style.color = "red";
valid = false;
} else {
errorTypetextLable.innerHTML = "";
errorTypetextLable.style.color = "";
}
if (errorTitletext.value.length === 0 || errorTitletext.value === " ") {
alert("You must create a title");
errorTitleLable.innerHTML = "*Please create a title";
errorTitleLable.style.color = "red";
valid = false;
} else {
errorTitleLable.innerHTML = "";
errorTitleLable.style.color = "";
}
if (errorContenttext.value.length === 0) {
alert("You must enter content");
errorContentLabel.innerHTML = "*Please enter content";
errorContentLabel.style.color = "red";
valid = false;
} else {
errorContentLabel.innerHTML = "";
errorContentLabel.style.color = "";
}
return valid;
}
Demo: Fiddle

JavaScript Alert/Confirm Error

Currently when new users register at my website, they have to fill out some forms. If their password is too short, doesn't match, they don't fill out all of the fields, or any other error, I want to alert them of it. Currently it does not alert them, so I switched to confirm. That didn't work either so I considered using showModalDiaglog. That also didn't work, I am out of Ideas. I currently have this:
HTML
<form>
First Name:<br/> <input id="firstname"/><br/>
Last Name: <br/> <input id="lastname"/><br/>
Age: <br/> <input id="age"/><br/>
Your Email:<br/> <input id="email"/><br/>
Username: <br/> <input id="username"/><br/>
Password: <br/> <input id="password"/><br/>
Confirm Password:<br/> <input type="password" id="passwordconfirm"/><br/>
<br/>
<button size=20 onClick='getRegistrationFields()'>Submit</button>
</form>​
JavaScript
function getRegistrationFields() {
var first = document.getElementById("firstname").value;
var last = document.getElementById("lastname").value;
var email = document.getElementById("email").value;
var age = document.getElementById("age").value;
var username = document.getElementById("username").value;
var password = document.getElemetnById("password").value;
var confirm = document.getElementById("passwordconfirm").value;
var empty = "";
if ((first === empty) || (last === empty) || (email === empty) || (age === empty)
|| (username === empty) || (password === empty) || (confirm === empty)) {
var message = "Not all of the fields are filled out";
prompt(message);
//showModalWindow("fields");
return false;
}
else {
age = parseInt(age);
if (password.length < 10) {
var message2 = "Password must be at least 10 characters long";
prompt(message2);
//showModalWindow("passwordlength");
return false;
}
else if (password != confirm) {
var message3 = "Passwords Do not match";
prompt(message3);
//showModalWindow("passwordmatch");
return false;
}
else if (age < 18) {
var message4 = "You must be older to register for this software.";
prompt(message4);
//showModalWindow("young");
return false;
}
else {
var message5 = "All of the fields are correct. We will be processing your request";
prompt(message5);
//showModalWindow("success");
return true;
}
}
}
function showModalWindow(fileName) {
window.showModalDialog("alerts/" + url + ".html", "", "resizable: no; height: 150; width: 350;");
}
try
html:
<button size="20" id="btn_submit">Submit</button>
js:
var btn_submit = document.getElementById("btn_submit");
btn_submit.onclick = getRegistrationFields;
Make it easy on yourself.
<input type="password" class="password" />
<input type="text" class="age" />
<script type="text/javascript">
!(function () {
var txBxs = document.querySelectorAll('input[type=textbox]'),
i = txBxs.length;
while (i--) {
tkBxs[i].onchange = textBoxCheck;
};
}());
//
function textBoxCheck() {
//
switch (this.class) {
//
case 'password':
if (this.value.length < 10)
{ alert('Password to short'); };
break;
//
case 'age':
if (+this.value < 18)
{ alert('To young kiddo!'); };
break;
};
};
</script>
There is a typo:
var password = document.getElemetnById("password").value;
You wrote getElemetnById instead of getElementById.

Categories

Resources