How do I change the format of digit inputs - javascript

Basically, I want to change a person input from 0######### to (0#)########, the event im using is onblur
function numberChange(){
var check = document.getElementById("number").value;
var regCheck = /^[0-9]+$/;
if (check != 10 || !regCheck)
{
alert("Please input your 10 digit mobile number")
return false;
}
else if (check == 10 || regCheck)
{
return true;
}
}

Your regCheck should be ^\(0\d\)\d{8}$
Demo
Update :
This regex validates the number of characters, you can omit length check in your code :
function numberChange(){
var check = document.getElementById("number").value;
var re = new RegExp(/^\(0\d\)\d{8}$/);
if (re.test(check)) {
return true;
}
else {
alert("Please input your 10 digit mobile number")
return false;
}
}

This will check for 10 digits, first number is zero, and that all inputs are digits. Once all of that passes the code will add the '(' & ')' to it. This approach gives specific errors depending on how the user incorrectly entered the number.
<html>
<body>
Phone number: <input type="text" id="number" onblur="checkNumber()">
<script>
function checkNumber() {
var x = document.getElementById("number").value;
// Check for 10 digits.
if(x.length != 10) {
alert('The number must be 10 digits.');
return false;
}
// Make sure the first digit is 0.
if(x.charAt(0) != 0) {
alert('The first digit must be 0.');
return false;
}
// Make sure all digits are numbers and not characters.
if(isNaN(x) == true) {
alert('All digits must be numbers.');
return false;
}
// If here then everything else passed so add the '(' and ')' to the number.
document.getElementById("number").value = '(0' + x.charAt(1) + ')' + x.substring(2, 10);
}
</script>
</body>
</html>

Related

Validating Password has a digit

So everything works in the following code, except for the validation of whether or not a password has a numerical digit. Can anyone see what may be wrong with my code here? It's acting like my password passes the test for numerical digits when it doesn't.
// Too short
//var password = "pass";
// Contains a space
// password = "Contains space";
// Doesn't use a digit
password = "my-password";
// Repeats first and last 3 chars
//password = "abc123abc";
// Strong password
// password = "StrongPassword1";
// See if function returns an error message or not
var message = testPassword(password);
if (message) {
console.log(message);
}
else {
console.log("Password accepted.");
}
function testPassword(password) {
var n = password;
// Returns true if n is a string with a single digit, false otherwise
var hasDigit = function isSingleDigit(n) {
var unicodeValue = n.charCodeAt(0);
return n.length === 1 && unicodeValue >= 48 && unicodeValue <= 57;
};
if (password.length < 6){
return "Password must be at least 6 characters.";
}
if (password.indexOf(" ") != -1){
return "Password may not contain a space.";
}
if (hasDigit === false){
return "Password must have at least one digit.";
}
if (password.substr(0, 3) === password.substr(-3)){
return "The password may not begin and end with the same 3 characters.";
}
// Everything is good
return "";
}
Console output:
Password accepted.
EDIT: Here was the fix. Thanks awesome community!
var n = password;
// Returns true if n is a string with a single digit, false otherwise
function isSingleDigit(n) {
var unicodeValue = n.charCodeAt(0);
return n.length === 1 && unicodeValue >= 48 && unicodeValue <= 57;
}
var hasDigit = isSingleDigit(n);
The variable hasDigit has the definition of the function itself and not the return value since it was never called.
Change your if statement to
if (hasDigit(n) === false){
return "Password must have at least one digit.";
}
Edit
However, I don't think the function would still work correctly as this function would only return true if the passwordis a single digit as opposed to a string containing at least one digit.

Limit numbers before and after decimal point on input number

How to limit numbers for before and after the decimal point, something like 123.123 , so it can have max 3 numbers before . and max 3 numbers after .
<div class="form-group">
<input type="number" class="form-control" name="ta" id="ta" placeholder="ta" ng-model="ta.kol" ng-maxlength="15"/>
<p ng-show="taForm.kol.$error.maxlength" class="help-block">Max 15 symbols !</p>
</div>
You can add a onchange event on the input field and call a function that validates the current input value using regex and communicate same to the user.
Regex : ^[0-9]{0,3}.?[0-9]{0,3}$
JS Code to validate:
function validateNumberInput(inputNumber){
return number.search(/^[0-9]{0,3}.?[0-9]{0,3}$/) == 0 ? true : false;
}
Also you can write a directive in angular that can handle the same.
This can be solved with a simple piece of javascript if you just add an Event Listener to the input and then split the input on the decimal point you can then check the length of both parts and act accordingly.
https://jsfiddle.net/pk07net6/
function checkNumbers()
{
console.log(this.value);
var numbers = this.value.split('.');
var preDecimal = numbers[0];
var postDecimal = numbers[1];
if (preDecimal.length>3 || postDecimal.length>3)
{
alert("Max 3 numbers before and after the decimal point.")
this.select();
}
}
//ADD LISTENER TO INPUT
var input = document.getElementById("numberInput");
console.log(input);
input.addEventListener("change", checkNumbers)
You can use ng-pattern with a regex:
<input ng-pattern="/^[0-9]{1,3}(\.\d{0,3})?/" />
docs: https://docs.angularjs.org/api/ng/directive/ngPattern
For the fraction its pretty easy as you can use Angular number filter. As for the number before the digit you should create a filter like this :
app.filter('beforeDigit', function ($filter) {
return function (input) {
if (input>1000)
return (input % 1000)
elseif(input<1000)
return input;
};
});
So in the end you will end up with something like this :
{{val | filter:{number:3}, filter:beforeDigit }}
After hours of work, I create java-script function which work on keypress event. Number can be 8 characters before decimal separator and 2 character after decimal separator.
https://codepen.io/dumbelovic/pen/bvdXXq
function BeforeAfter(e, obj) {
sepDec = "."
var keycode;
var fieldval = obj.value;
if (window.event) keycode = window.event.keyCode;
else if (e) { keycode = e.which; }
else { return true; }
// denided first charatcter to be zero
if (fieldval == "" && keycode == 48)
return false;
// denided first character to be decimal point
if (fieldval == "" && (keycode == 44 || keycode == 46))
return false;
// enter first decimal point,
// but every next try to eneter decimal point return false
if (fieldval != "" && ((keycode == 44 || keycode == 46))) {
if (fieldval.indexOf(sepDec) < 0) {
var newValue = fieldval + sepDec;
$(obj).val(newValue);
}
return false;
}
var splitfield = fieldval.split(sepDec);
var beforeDecimalPoint;
var afterDecimalPoint;
if (splitfield.length == 1) {
beforeDecimalPoint = splitfield[0];
afterDecimalPoint = "";
}
else if (splitfield.length == 2) {
beforeDecimalPoint = splitfield[0];
afterDecimalPoint = splitfield[1];
}
if (beforeDecimalPoint.length == 8 && keycode != 8 && keycode != 0) {
if (obj.selectionStart >= 0 && obj.selectionStart <= 8)
return false;
}
if (afterDecimalPoint.length == 2 && keycode != 8 && keycode != 0) {
if (obj.selectionStart >= beforeDecimalPoint.length + 1 && obj.selectionStart <= beforeDecimalPoint.length + 1 + 2)
return false;
}
return true;
}

How to get alerts for inputed name length of characters - javascript

Hello im trying to do a simple script here when i enter name in input field, i want to get certain alerts for example:
- if name is > 20 characters alert = "name is bigger than 20"
- if name is between 12 and 20 alert = exact number of chars of the name that was inputed
- if name is bigger than 2 chars and bigger or equal than 20 = alert that name
this was just an example of what im trying to do, but im just noob at this point im only 1 month into javascript(html and css) so if anyone can point me in the right direction i would appreciate.
Ok, so far i have this:
<form name="myForm" id="form2" onsubmit="return validate()">
Input name: <input type="text" name = "myName" id="t" />
<input type="submit" name="submit" value="submit" />
</form>
function validate() {
if(document.myForm.myName.value.length>20){
alert("your name is too big");
submitFlag=false; // im not sure what this line does //
} else if(document.myForm.myName.value.length=12-20){
alert("your name is" + document.myForm.myName.value.length + " chars");
} else if(document.myForm.myName.value.length=0){
alert("input name")
}else{
alert("ok e")
}
return submitFlag;
}
THe if statements are workin only if i have two, im getting only the first 2 alerts, so i would like to input more else if statements and to get alerts for them also, i tried to put some more myself, but the dont work, im only getting the first two.
Extending what #dfsq have said,.. you try to get:
if name is between 12 and 20
that means smth like:
document.myForm.myName.value.length > 12 && document.myForm.myName.value.length <= 20
And make your code more simple and readable. And don't forget to return false (your submitFlag):
function validate() {
var len = document.myForm.myName.value.length;
if (len > 20)
{
alert("your name is too big");
}
else if (len > 12 && len <= 20)
{
alert("your name is" + len + " chars");
}
else if (len == 0)
{
alert("input name");
}
else
{
//in fact it would alert when name between 0 and 12
alert("ok e");
}
return false;
}
There are a difference between operators. = is an assignment, == and === are comparison operators. You need latter:
document.myForm.myName.value.length == 0
Here we go:
function validate() {
var charLength = document.myForm.myName.value.length,
submitFlag = false; // This flag would be used further to stop the use going ahead from this particular validation
if (charLength > 20) {
// length more than 20
alert("your name is too big");
} else if (charLength <= 20 && charLength > 12) {
// length between 20 and 12
alert("your name is" + charLength + " chars");
} else if (charLength == 0) {
// If no input there
alert("enter name");
} else {
// Otherwise in success condition
alert("ok e");
submitFlag = true;
}
return submitFlag;
}
Jsfiddle: http://jsfiddle.net/fcwbkkd7/

Checking for alphabet and numeric chars in a field

I am trying to write javascript code for making sure a field in my form has its first 2 characters as alphabets (US) and the rest 8 are numerics.
The total has to be 10, and if any of these are not satisfied, I should throw up an alert box.
I am checking for numerics now but I don't know how to combine checking for alphabets and numerics in the same field.
Here is my code for checking for numerics.
Please help me out! sid is my field name.
// only allow numbers to be entered
var checkOK = "0123456789";
var checkStr = document.forms[0].sid.value;
var allValid = true;
var allNum = "";
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.charAt(i);
for (j = 0; j < checkOK.length; j++)
if (ch == checkOK.charAt(j))
break;
if (j == checkOK.length)
{
allValid = false;
break;
if (ch != ",")
allNum += ch;
}
if (!allValid)
{
alert("Please enter only 8 numeric characters in the \"sid\" field.");
return (false);
}
}
A single regular expression will easily perform this check :
/^[a-zA-Z]{2}\d{8}$/
/^ match beginning of string
[a-zA-Z]{2} match exactly 2 alphabetic characters
\d{8} match exactly 8 digits
$/ match end of string
Use as follows :
/^[a-zA-Z]{2}\d{8}$/.test (str) // Returns true or false
You can use regexp. jsfiddle
var regExp = /[a-z]{2}[0-9]{8}/i;
var text = 'ab12345678';
if(text .replace(/[a-z]{2}[0-9]{8}/i, "").length > 0){
alert("Please enter only 8 numeric characters in the \"sid\" field.");
return (false);
}
Simple regular expression, checks for 2 characters + 8 digits
var checkStr = document.forms[0].sid.value;
if (checkStr.match(/\b[A-z]{2}[0-9]{8}\b/) === null) {
alert("Please enter only 8 numeric characters in the \"sid\" field.");
return (false);
}
/^([a-zA-Z]{2}\d{8})$/; should check for 2 characters and then 8 decimals.

JavaScript - how to validate field to allow certain character and certain length

I need to validate a textbox, so it's value consist of 10 characters (not more, not less). The below code does it, allowing me to set the restricted length for each field separately.
function charLength(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
alert("Invalid number of characters");
elem.focus();
return false;
}else{
return true;
}
}
and this is how I'm calling it:
onBlur="charLength(document.getElementById('tf1'),1,9)"
but the field that I validate must not only be 10 characters long, but it also has to start with letter Z.
How would I do such validation? is it possible in the first place?
try it also:
function charZ10(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max && uInput.substr(0, 1) == "Z"){
alert("Material number has to consist of 10 characters begining with Z");
elem.focus();
return false;
}
else return true; //i
}
and try to add maxlength in the textbox
<input type="text" maxlength="10">
function charZ10(elem, min, max){
var uInput = elem.value;
if(uInput.length == 10 && uInput.substr(0, 1) == "Z")
return true;
alert("Material number has to consist of 10 characters begining with Z");
elem.focus();
return false;
}
function charZ10(elem) {
var pass = /^Z.{9}$/.test(elem.value); // 10 chars starting with Z
if (!pass) {
alert("Try again, noob.");
elem.focus();
}
return pass;
}
Must be
if(uInput.length <= 10 && substr(uInput,0, 1) == "Z")

Categories

Resources