Validating Input in Javascript - javascript

I'm working on a page that has a text box and a button (there's more to it, but these are the things that are giving me trouble). When the button is clicked, it's supposed to verify that there are only 3 letters entered in the text box.
Here is the html creating the input box and button:
<form>
Enter 3 letters: <input type="text" id="3letters"> <br>
<input type = "button" id = "check" value = "Send" onclick="validate()">
</form>
And here is the Javascript function to check the input:
function validate() {
var TTinput = document.getElementById("3letters").value;
if(TTinput < 3) {
alert("Please enter 3 letters");
}
}
To test that this works I'm trying to enter only a single letter, but when I click the button, nothing happens. Any idea what I can do to fix this?

Check the length property:
if (TTinput.length < 3)

What you are doing is to set to the TTinput variable the value of the text box. So now TTinput contains a string. What you need is to get its length, and the length of a string in javascript can be got by the lenght property:
var str = "ABCD";
str.length; // 4
http://www.w3schools.com/jsref/jsref_length_string.asp
function validate() {
var TTinput = document.getElementById("3letters").value;
var input_length = TTinput.length;
if(input_length < 3) {
alert("Please enter 3 letters");
}
}

If you want exactly 3 characters use:
if(TTinput.length < 3 || TTinput.length > 3) {
alert("Please enter 3 letters");
}
or
if(TTinput.length != 3) {
alert("Please enter 3 letters");
}
*This (TTinput.length < 3) alone will consider 4, 7, 350,... characters valid.

Related

Do form validation in Javascript

I have a form in which I have a field where the user enters their phone number and we force them to start with +34 followed by 9 digits (12 digits in total are what that field should have), but then when I change at +31 for example I pick it up as if it were +34, this is using a
<input type="text">
This is a variable
let phone2 = phone.length
This is the contidion I am using in Javascript
if (phone != '+34' & phone2 < 12) {
evt.preventDefault ();
alert ('The phone number must start with +34 and have at least 12 digits');
}
If anyone can help me
Try this:
Note that onblur means that the test function will fire when the input field loses focus. So, to run the test, type something and then click outside the input field.
const $ = document.querySelector.bind(document);
function test() {
const phone = $('input').value;
if (phone.substr(0, 3) !== '+34' || phone.length < 12) {
alert('The phone number must start with +34 and have at least 12 digits');
} else {
alert('good job');
}
}
<input onblur="test()" placeholder="Phone (must begin with +34)" />

How to allow only numbers between 0 to 30 or A,D character in input using javascript?

Hi i have created a javascript function to only allow numbers between 0 to 30 and character A and D. I give an alert if it does not match the criteria but if the user clicks ok on the alert the values still remain in the input and can be updated in the database. I want that user should not be able to enter anything at all in the input box except character A , D and numbers between 0 to 30 like it is done in the case of input type=number we can only enter numbers. My javascript function is:-
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
The javascript works fine with validation but after clicking ok in alert value still remains there and it also gives error when input box is empty any way to avoid that. Is there any other better way to create the function or can it done by using jquery. I am new to jquery if it is possible to do it with jquery it would be great. I would be highly gratefull if anybody can help.
You may try this code example.
function validate(box) {
var val = box.value;
if (!/^[AD]?$/.test(val) && isNaN(val) || (0 > val || 30 < val)) {
box.value = '';
alert('Only A or D or 0-30');
}
}
<input type='text' value='30' onblur='validate(this);' />
The best solution would be to check it at the moment when you are inserting it in the database.
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
If you want to make sure there is no error when the text is empty, you can do this. The .replace part is to ensure that if the text input is filled with only spaces, it is considered empty.
With the rest of the function:
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
How about replacing disallowed values so only the desired input is allowed. With this you won't be able to enter anything other than A, D and numbers 0 - 30:
$('input').on('input', function(e) {
this.value = this.value
.replace(/[^AD\d]/, '')
.replace(/(3)[1-9]/, '$1')
.replace(/(30)[0-9]/, '$1')
.replace(/([4-9])[0-9]/, '$1')
.replace(/([\d][\d])[\d]/, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" />
Note, it's still a good idea to do some server side validation.

JavaScript Form Validation for Textarea with Multiple Values

How would I implement error checking of multiple values entered into a textarea? I need to make sure that the values entered use commas as a delimiter before the form is submitted.
You can use
value.split(",")
to separate each word and individually validate them and
value.split(",").length < 2
to check if commas were entered. Should be good to get you started.
Update: I have update the fiddle with your new inputs. It includes check for empty inputs before or after comma, and it trims out spaces before validation
Working example here
Here is a sample implementation:
Markup
<textarea id="textarea" placeholder="comma separated values"></textarea>
<span id="msg"></span>
<br>
<button onclick="submit()">Submit</button>
Script
function isValid() {
var value = document.getElementById("textarea").value;
var values = value.split(',');
if(values.length > 0 && values.length < 5){
for(var i =0;i<values.length;i++);{
if(parseInt(values[i]) === NaN) return false;
}
return true;
}
return false;
}
function submit(){
if(isValid()){
document.getElementById("msg").innerText = "Valid";
//submit the form
} else {
document.getElementById("msg").innerText = "not a valid input";
}
}

condtion in javascript validation not working properly

I have a textbox and a submit button
<input type="text" name="username" id="username"/><br/>
<input type="submit" onclick="return validate()"/>
Here is the function code:
if (document.getElementById("usernameee").value == null || document.getElementById("usernameee").value == "" ) {
document.getElementById("usernameee").style.borderColor = 'red';
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
if (document.getElementById("usernameee").value.length!=0 || document.getElementById("usernameee").value.length < 8 ) {
document.getElementById("usernameee").style.borderColor = 'red';
document.getElementById("message").innerHTML="Enter Atleast 8 Characters"
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
}
now what is want is that if the user leaves the filed empty it should only highlight the textbox with backgound color red and if the username is less than 8 characters it should show the message and highlight the backgound of textbox but now even if the textbox is empty it is displaying the message which i dont want...if the field is empty it should ol
I think your second conditional is wrong. Also you can write the code much cleaner like this:
var username = document.getElementById("usernameee");
if(!username.value) {
//There is no username
username.style.borderColor = 'red';
} else if(username.value.length < 8) {
//There is a username and the value is shorter than 8 characters
username.style.borderColor = 'red';
document.getElementById("message").innerHTML = "Enter Atleast 8 Characters";
} else {
//There is a username and it is longer than or equal to 8 characters.
username.style.borderColor = '';
document.getElementById("message").innerHTML = "";
}

Comparing two input fields

I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions.
<script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>
<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>
A tidy way to do it which is easy to read:
var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;
if (firstInput === secondInput) {
// do something here if inputs are same
} else if (firstInput > secondInput) {
// do something if the first input is greater than the second
} else {
// do something if the first input is less than the second
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Here's a suggestion/hint
if (Math.abs(v1 - v2) <= 1) {
alert("can't have duplicate!");
return false;
}
And here's the jsfiddle link, if you want to see the answer
Give them both IDs.
Then use the
if(document.getElementById("first").value == document.getElementById("second").value){
//they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
//first is more than second
}
and so on.

Categories

Resources