String length as you are typing in javascript - javascript

I set the character validation for a password input to be 8. I want to input a function or an instruction (as the case may be) in javascript so that as I am typing the password, the background will be red if it isn't up to 8 characters yet and it would change to green if it has reached 8 characters and above

Try this :
function checkLength(textField) {
var strText = textField.value;
// if without spaces
strText = strText.replace(/^\s+|\s+$/g,"");
if(strText.length > 8) {
textField.style.backgroundColor = "#ff0000";
} else {
textField.style.backgroundColor = "#00FF00";
}
}
<input type="password" name="sometextfield" onkeyup="checkLength(this);" />

Related

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.

Reformat and return textarea input

Can someone help me with a working html/jquery script that will read the text input of an html textarea box and test if the text input on the box contains a numeric string of 11 characters as part of its content, if it does, the script should come up with a dialog box that will ask if the client will like to reformat that numeric content of the textarea box. if the yes option of the dialog box is selected by the client, the script should then reformat the numeric string by adding spaces after the 3rd, 6th and 9th characters e.g change 08293434565 to 082 934 345 65, and thereafter return the reformatted data into the html textarea box
function Confirm() {
var data = $('#fix').val();
var arr = data.split(' ');
//check if numeric and 11 numbers
if (isNaN(arr[5]) == true && arr[5].length == 11) {
//show popup, if yes run the format function
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (window.confirm("Message contains numeric characters which might make the message not delivered to some networks. Do you want us to reformat the message ?. This might increase the numbers of pages of the message and the cost?")) {
confirm_value.value = "Yes";
format();
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
}
function format() {
var first = arr[5].substring(0, 4);
var second = arr[5].substring(4, 20);
second = second.replace(/(.{3})/g, "$1 ")
$('#fix').val("This is my mobile number " + first + " " + second);
};
<input type="textbox" id="fix" name="fix" />
<button ID="button1" OnClick="Confirm();" runat="server">Confirm</button>
Your test for numeric and 11 numbers isn't correct.
function Confirm() {
var data = $('#fix').val();
//check if numeric and 11 numbers
if (!isNaN(data) == true && data.length == 11) {
//show popup, if yes run the format function
if (window.confirm("Message contains numeric characters which might make the message not delivered to some networks. Do you want us to reformat the message ?. This might increase the numbers of pages of the message and the cost?")) {
format(data);
}
} else {
alert('Check number format');
}
}
function format(data) {
var first = data.substring(0, 4);
var second = data.substring(4, 20);
second = second.replace(/(.{3})/g, "$1 ")
$('#fix').val("This is my mobile number " + first + " " + second);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="textbox" id="fix" name="fix" />
<button ID="button1" OnClick="Confirm();" runat="server">Confirm</button>

How do I allow the user to only input a string?

function EnterCandidates() {
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function(label, index) {
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
});
}
I have this code which gets the users input and changes the label with it but i want to add some code which only allows the user to enter letters of the alphabet. How would I go about this using this code?
If you are using modern browsers then user html5 validation -
<input type="text" name="name" class="field" pattern="[a-zA-Z ]+" />
It accepts a-z and A-Z plus space
listen to keyDown event and match with this regex:
/[a-zA-Z]+/
if you're targeting modern browsers only, you can try this:
<input type="text" pattern="[a-zA-Z]" title="Only letters" />
you can't avoid that the user types non alphabetic characters. But you can:
- control the input fields (onkeydown) and check if there are some characters you don't want Stackoverflow - force input to only alpha-letters
- do the same before the
label.textContent = candidateNameInputs[index].value;
line and filter/replace the characters you don't want
var val = document.getElementById('id').value;
if (!val.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
return false;
}
full script
function EnterCandidates() {
console.log('woo');
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function (label, index) {
if (!candidateNameInputs[index].value.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
}
else
{
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
}
});
}
Here is one way to do it using Javascript.
http://jsfiddle.net/q60gm0ra/
var input = document.getElementById('alpha');
input.addEventListener('keypress',function(e) {
var str = String.fromCharCode(e.charCode);
if (!(/[A-Z]|\s/i).test(str)) {
e.preventDefault();
}
});

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 = "";
}

How to use this Javascript checkAlphaNumeric() with HTML?

I am stumped. I have the following code and cannot get it to work right. I'm kind of using a password or email validation event of onkeyup, but I really just want it to work if I click on submit. My form is already using validateForm() and checkPass(). I just need to get this to work.
// *********** ALPHA-Numeric check ***************************
function checkAlphaNumeric()
{
var passw = document.getElementById("_password");
var mystring=new String(passw)
var authpassword = document.getElementById("AuthPass");
if(mystring.search(/[0-9]+/)==-1) // Check at-least one number
{
authpassword.innerHTML = "<span class='smaller'>*Password must be 8 characters, 1 letter, and 1 number!</span>!";
return false;
} else {
count++;
document.getElementById("err_password").innerHTML="";
}
if(mystring.search(/[A-Z]+/)==-1 && mystring.search(/[a-z]+/)==-1) // Check at-least one character
{
authpassword.innerHTML = "<span class='smaller'>*Password must be 8 characters, 1 letter, and 1 number!</span>!";
return false;
} else { count++;
document.getElementById("err_password").innerHTML="";
}
} //*** END FUNCTION
HTML CODE IS BELOW
<input id="_password" type="password" name="password" autocomplete="off" size="40" onkeyup="checkAlphaNumeric(); return false;"><span id="AuthPass" class="AuthPass" style="font-size: smaller; color:red;""></span>

Categories

Resources