How to put function using string control - javascript

On this first Image I would like to declare a variable that is string that would be used for making a condition if the username that is input if the string has 5 numbers it would be tag as EmployeeID if string has 10 numbers it would be tag as studentID.
So that before I create another app for User Interface for Employee and Student it would then evaluate.

I am not able deduce the code language, but I will write down a function considering that it's a jQuery.
var Id = "" , type = "";
if($("#Userid").val().length = 5)
{
Id = $("#Userid").val();
type = "employee";
}
elseif($("#Userid").val().length = 10)
{
Id = $("#Userid").val();
type = "student";
}
else
{
alert("Invalid ID");
}
Hope that's help! Now you can check type variable to decide the type of current logged in user.

Related

remove email address format from username

var login_id = 'sa-testaccount0125#abc.com';
console.log(login_id.substring(0, login_id.lastIndexOf("#")));
Above script works perfectly if I pass input with '#abc.com'. Does not work if string do not have '#domain.com'
We have some user name with username#domain.com and few are just username. I want extract #domain.com from user name. Expected output is if input is username#domain.com return output = username and if input is username, output should be username.
Please help if there is any way.
Use .split() method to split your string in parts
It will still work if you do not have #domain.com
Case-1:
const login_id = 'sa-testaccount0125#abc.com';
console.log(login_id.split("#")[0])
Output
"sa-testaccount0125"
Case-2:
const login_id = 'sa-testaccount0125';
console.log(login_id.split("#")[0])
Output
"sa-testaccount0125"
If you split on # then you get an array of items. The first item of the array will be the username, whether there was a # in it or not.
const test = str => str.split('#')[0]
console.log(test('sa-testaccount0125#abc.com'));
console.log(test('sa-testaccount0125'));
You're already using a indexOf. Usee that to check # if exists as well:
function check(login_id) {
if (login_id.indexOf('#') >= 0) {
return login_id.substring(0, login_id.lastIndexOf("#"));
}
return login_id;
}
console.log(check('sa-testaccount0125#asdasdasd.com'));
console.log(check('sa-asd'));
console.log(check('sa-asasd#domain.com'));
check first if it contains the '#' charactar first
login_id.includes('#') ? console.log(login_id.substring(0,
login_id.lastIndexOf("#"))) : console.log(login_id) ;
Running example
function username(login_id) {
return login_id.includes('#') ? login_id.substring(0,login_id.lastIndexOf("#")) : login_id ;
}
console.log(username("sa-testaccount0125#abc.com")) ;
console.log(username("sa-testaccount0125")) ;

How do I restrict input in the ion-input?

I am trying to restrict the user of inputting numbers by removing and not visualizing them.
in html
<ion-input type="text" [(ngModel)]="firstName" (ionChange)="check($event)"></ion-input>
in .ts
check(event){
let value : string = event.detail.value;
event.detail.value = value.replace(/[0-9]/g,'')
}
With this code I expected for the user not to see if he inputs numbers. However the value of firstName changes, but the user still sees characters and numbers.
create one function
public onKeyUp(event: any) {
let newValue = event.target.value;
let regExp = new RegExp('^[A-Za-z? ]+$');
if (! regExp.test(newValue)) {
event.target.value = newValue.slice(0, -1);
}
}

Trying to generate username Javascript

Before I start I should mention i'm a complete novice and I apologise if this code is horrific.
I'm trying to create a username using first initial and surname to be ouputted with a welcome message of "hello Username, welcome to myfunction!".
I'm suppose to use a string to attach the initial and surname together then concatenate the first character of string 1 with string 2 and store the username.
any help would be appreciated as this is for school.
here's what I have so far...
<!DOCTYPE html>
<script type = "text/javascript">
// GenerateUsername Function
function GenerateUsername ()
{
var x;
var firstInitial = prompt("Please enter your initial of your first name");
var surName = prompt("please enter your surname");
var user = new Array();
firstInitial [0] = "user";
surName [1] ="user";
document.write(firstInitial + surName);
}
if (user == 0)
{
alert("welcome, " + user);
}
</script>
I think this might can help you. return value from function call and then bind in alert
function GenerateUsername ()
{
var x;
var firstInitial = prompt("Please enter your initial of your first name");
var surName = prompt("please enter your surname");
var user = new Array();
firstInitial [0] = "user";
surName [1] ="user";
return firstInitial[0] + ' ' + surName[1];
}
if (user == 0)
{
alert("welcome, " + GenerateUserName());
}
if you want to call your function when your page is loaded you have to add the attribute onload="GenerateUsername()" on a html tag.
Also you should place your javascript in a different file and comment your code (it is easy to understand it but if you're a total beginner in javascript you will probably not remember what's the difference between prompt and alert in some days for example).

Javascript prompt() alternative - Waiting for user response

I would like to ask series of questions to users in one function.
If I use prompt(), it is possible to ask all the questions in one function.
function question(){
var name = prompt("Enter your name");
var age = prompt("Enter your age");
}
But if I try to use input tag, this is impossible.
function question(){
document.write("Enter your name");
// you can't wait until the user responds. It will simply execute all the lines at once.
name = document.getElementById("input").value;
document.write("Enter your age");
age = document.getElementById("input").value;
}
If I do this, I can't use input tag to ask questions to users in one function. How can I wait until the user responds?
To chain prompts you can do something like:
const name = prompt("Enter your name");
if (!!name) {
const age = prompt("Enter your age");
if(!!age){
...
}
}
Or if you can use rxjs 5.5+ in your project you can use an observable to wait for the first prompt.
For example:
of(prompt("Enter your name"))
.pipe(first(), filter((name) => !!name))
.subscribe((name) => {
var age = prompt("Enter your age")
if(age) {
...
}
});
You can keep all your input boxes disabled except the first one. The second one can be enabled upon the user response to the first one. The line of inputs will go on like this.
Here is a little demonstration. Please note this is only a sample code which shows you the design pattern.
<input id="name"></input> <button onClick="getInput()">Ok</button>
<input id="address"></input> <button onClick="getInput()" disabled>Ok</button>
and in JS
var name, address;
functon getInput() {
name = document.getelementById("name").value;
address = document.getElementById("address").value;
if (address !== "")
document.getElementById("address").removeAttribute("disabled");
}
There are many advance methods than this is available in JS. But probably you should study this pattern first.
You cant take 2 different values from the same input in a function. You should create another input or some button to differentiate variables. For example:`
Enter your name
Enter your age
Save
var bSave = window.document.getElementById('bSave');
bSave.addEventListener("click", question);
var newName = window.document.getElementById('iName');
var newAge = window.document.getElementById('iAge');
function question() {
name=newName.value;
age=newAge.value;
}
</script>
`
document.write() is to writes HTML not for asking user input like prompt(). what you need is input validation before user submit the form like
function checkQuestion(){
if(document.getElementById("name").value == "")
alert('name empty');
if(document.getElementById("age").value == "");
alert('age empty');
}

ServiceNow Script onSubmit not working properly

I am using ServiceNow platform. I am writing a Catalog Client Script to validate form fields on a Catalog Item record producer.
I am stopping the submission of the form by using return false if validation does not pass inspection.
I have tested this by entering invalid data (group name with special characters or a group name that exists already) and it catches the issue and shows the error message. I can enter invalid data and submit multiple times and it works.
However, the issue:
The script seems to "stop" running after I first enter invalid data and submit, and then I correct the data press the submit button again. It just sits there and does nothing. I have to reload the form again which is not desirable.
What is going on with the control flow? How can I cleanly stop the form if the data is invalid, but then allow the user to correct the mistake and press the submit button again to proceed?
I can tell that the script doesn't run again because I have an alert box popping up that says "script run" every time the script runs. It just stops running at some point after submitting invalid data first and then entering some valid data and pressing submit.
function onSubmit() {
g_form.hideAllFieldMsgs('error');
alert("script run");
//Group Name contain letters numbers and dashes only
var group_name = g_form.getValue('u_group_name');
// Group name regular expression
var regGrpName = /^([A-Za-z0-9\-]+)$/;
// Check name against regular expression
if (regGrpName.test(group_name) == false) {
g_form.showFieldMsg('u_group_name', "Group Name must contain only letters, numbers or dashes. ", 'error');
//Do not submit
//g_form.submitted = false;
return false;
}
//Check if google group already exists
var rec = new GlideRecord('u_google_user_accounts');
rec.addQuery('u_account_email', new_group_email);
rec.query();
while (rec.next()) {
g_form.showFieldMsg('u_group_name',rec.u_account_email + " already exists as an account.",'error');
return false;
}
//Group Members Email List separated by commas
// Hide error message
//g_form.hideErrorBox('u_group_members');
var group_members = g_form.getValue('u_group_members');
// Comma separate list
var member_split = group_members.split(',');
// Loop over list of email addresses
for (var n = 0; n < member_split.length; n++) {
// Trim whitespace
var member_info = trim ? member_split[n].trim() : member_split[n];
// Email validation regular expression
var regEmail = /^\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
// Check each item against regular expression
if (member_info.search(regEmail) == false) {
g_form.showFieldMsg('u_group_members', "Group Members contains an invalid email address. " + member_info, 'error');
//Do not submit
//g_form.submitted = false;
return false;
} else if (member_info.search(validRegExp) == true) {
g_form.setValue('u_group_members', group_members);
}
}
return true;
}
I'm glad you found a solution above, but I wanted to leave a comment as well, to ask if you've tried a try{} catch{} block to handle invalid data?
I think I have solved the issue. I made a completely separate function that checks the validation. The onSubmit calls the validation function and checks the return value. If the return value is false then it stops the form. Otherwise it is submitted even after multiple attempts with invalid data. I think this will do the trick. Let me know if anyone can see any issues. Thanks for the help.
function onSubmit() {
var isValid = checkGoogleGroup();
if (isValid == false) {
g_form.submitted = false;
return false;
}
}
function checkGoogleGroup() {
g_form.hideAllFieldMsgs('error');
//Group Name contain letters numbers and dashes only
var group_name = g_form.getValue('u_group_name');
// Group name regular expression
var regGrpName = /^([A-Za-z0-9\-]+)$/;
// Check name against regular expression
validGroupName = regGrpName.test(group_name);
if (validGroupName == false) {
g_form.showFieldMsg('u_group_name', "Group Name must contain only letters, numbers or dashes. ", 'error');
//Do not submit
return false;
}
//Check if google group already exists
var rec = new GlideRecord('u_broad_user_accounts');
rec.addQuery('u_account_email', new_group_email);
rec.query();
while (rec.next()) {
g_form.showFieldMsg('u_group_name',rec.u_account_email + " already exists as an account.",'error');
return false;
}
//Group Members Email List separated by commas
var group_members = g_form.getValue('u_group_members');
// comma separate list
var member_split = group_members.split(',');
// loop over list of email addresses
for (var n = 0; n < member_split.length; n++) {
// trim whitespace
var member_info = trim ? member_split[n].trim() : member_split[n];
// validation regular expression
var validRegExp = /^\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
// check each item against regular expression
if (member_info.search(validRegExp) == -1) {
g_form.showFieldMsg('u_group_members', "Group Members contains an invalid email address. " + member_info, 'error');
return false;
}
}
}

Categories

Resources