π NFSFU234 Form Validation Library


Hello || Salute || Hola || δ½ ε₯½ π
Table of Contents π
π Description
Introducing the NFSFU234 Form Validation library β yes, it's my very first attempt at creating something useful for the coding world. This little JavaScript gem is all about making sure your HTML form elements play nice and follow the rules. ππ¨βπ»
Now, I'm no expert, but I figured that validating forms could be a lot less painful. So, I cooked up NFSFU234 Form Validation. It's lightweight, beginner-friendly, and it's got a soft spot for textarea fields β those underappreciated champs. ππΆοΈ
Look, I'm not promising to solve every validation puzzle out there, but I did manage to make things easier. You can customize error messages to sound as friendly or as stern as you like. And those mandatory fields? Yeah, I've got their back. β
π
Oh, and if you're into stylish apps, NFSFU234 Form Validation offers ways to show errors that suit your app's vibe β whether it's neat little inline notes or those snazzy pop-up modals. π¨π₯
So, yeah, this is my debut library. I'm still learning the ropes, but I thought, why not share what I've got? Give NFSFU234 Form Validation a spin. It might not be perfect, but hey, it's my first shot at making developers' lives a tad easier. Enjoy! ππ
π οΈ Installation
To use the library in your project, there are two ways to include NFSF234 Form Validation JS Library:
βοΈ Using The CDN URL
If you're looking to employ the form validation library in your browser environment, simply include the following URLs within the <head>
tag of your HTML code:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nfsfu234-form-validation@latest/dist/css/nfsfu234FormValidation.min.css">
<script src="https://cdn.jsdelivr.net/npm/nfsfu234-form-validation@latest/dist/js/nfsfu234FormValidation.js"></script>
This way, your browser-based project can readily harness the capabilities of the NFSFU234 Form Validation library. ππ¦
βοΈ Install it via console:
If your preferred method involves npm
, yarn
follow these simple steps to integrate the NFSFU234 Form Validation library into your project:
- In your terminal, navigate to the desired project directory.
NPM
- Execute the following npm command to install the library:
npm install nfsfu234-form-validation --save
YARN
- Execute the following yarn command to install the library:
yarn add nfsfu234-form-validation
By executing this command, you're well on your way to enjoying the benefits of the NFSFU234 Form Validation library. π¦π
π Initialization
To harness the power of the NFSFU234 Form Validation library, you must first create an instance of the library with the appropriate parameters. Below are illustrative examples showcasing how to forge an instance with form particulars and AJAX options.
Example 1: Elementary Embarkation
In this scenario, we'll craft a straightforward NFSFU234 Form Validation instance sans any supplementary parameters. The library will adeptly detect the form with the ID 'jsSubmit' and inaugurate the validation process.
const formValidator = new NFSFU234FormValidation();
Example 2: Customized Form Insights and AJAX Artistry
This exemplar unveils the creation of a bespoke NFSFU234 Form Validation instance, replete with tailored form specifics and AJAX orchestrations.
const customErrorMessages = {
"text": "EMPTY FIELD",
"select": "SELECT FIELD IS REQUIRED",
"email": {
"empty": "EMPTY EMAIL",
"format": "The email is not in the right format",
},
};
const formDetails = {
form: "myForm",
isErrorMessageInline: true,
customErrorMessages: customErrorMessages,
};
const ajaxOptions = {
url: "login.php",
RequestMethod: "POST",
RequestHeader: {
"Content-Type": "application/json",
},
};
const formValidator = new NFSFU234FormValidation(formDetails, ajaxOptions);
In the second example, we furnish tailor-made error messages for the form fields and outline AJAX options for form submission. This approach empowers granular customization and mastery over the validation and form submission processes.
Note: If you initialize an instance of the NFSFU234 Form Validation Library without providing parameters, it will seamlessly detect the form with the ID 'jsSubmit' or the first form on the page in the absence of a form ID. This streamlined approach suits scenarios where you're working with a single form and prefer a simplified setup without additional configurations. ππ¨βπ»
π Available Functions in NFSFU234 Form Validation Library
Here you'll find a compilation of functions available within the NFSFU234 Form Validation Library. This comprehensive list showcases their function names, invocation methods, and succinct descriptions. Whether your playground is the browser or the Node.js console, these functions offer a range of capabilities to elevate your form validation game. Explore and employ them to create seamless user experiences! β¨π
1 | submit() | formValidator.submit() | Validates and submits a form. | β
| β |
2 | formValidator.validate():boolean | formValidator.validate(); | Checks and validate all the input elements (inputs, textareas, select, checkboxs, etc) | β
| β |
3 | ajax(AJAXOptions: Object): Promise | formValidator.ajax(AJAXOptions) | Makes an AJAX request using the provided options and returns a Promise with the server's response. | β
| β
|
4 | getAJAXResponse(): Promise | formValidator.getAJAXResponse(); | Retrieves the response from the last AJAX request made using the ajax function. It returns a Promise if available, or false if the AJAX request has been resolved. | β
| β
|
5 | generateRandomPassword(): string | formValidator.generateRandomPassword() | Generates a random password with length between 8 - 16 characters. | β
| β
|
6 | checkPassword(password: string, shouldIncludeSymbol: bool): boolean | formValidator.checkPassword('StrongP@ssword123', true) | Checks the strength of the provided password against criteria like minimum length, character types, and optional symbol inclusion. | β
| β
|
7 | isEmail(email: string): boolean | formValidator.isEmail('example@example.com') | Checks if the given email is in a valid email format. | β
| β
|
8 | isURL(url: string): boolean | formValidator.isURL('https://www.example.com') | Checks if the given string is a valid URL. | β
| β
|
9 | isZipcode(zipcode: string): boolean | formValidator.isZipcode('12345') | Checks if the given string is a valid ZIP code. | β
| β
|
10 | containsOnlyIntegers(inputValue: string): boolean | formValidator.containsOnlyIntegers('12345') | Checks if the given input value contains only integers. | β
| β
|
11 | countString(inputValue: string): number | formValidator.countString('Hello, World!') | Counts the number of characters in the provided input value. | β
| β
|
12 | togglePasswordVisibility(icons: Object, form: HTMLFormElement or string) | formValidator.togglePasswordVisibility({ 'show': 'ποΈ', 'hide': 'π' }, 'myForm'); | Enables password visibility toggle for password input fields within a form. | β
| β |
13 | validateInput(input: HTMLInputElement or string): boolean | formValidator.validateInput('usernameField') | Validates an input field with the specified ID or HTML input element. | β
| β |
14 | validateAllInput(): boolean | formValidator.validateAllInput() | Validates all input fields within the form. | β
| β |
15 | validateSelect(select: HTMLSelectElement or string): boolean | formValidator.validateSelect('countrySelect') | Validates a select field with the specified ID or HTML select element. | β
| β |
16 | validateAllSelect(): boolean | formValidator.validateAllSelect() | Validates all select fields within the form. | β
| β |
17 | validateTextarea(textarea: HTMLTextAreaElement or string): boolean | formValidator.validateTextarea('messageTextarea') | Validates a textarea field with the specified ID or HTML textarea element. | β
| β |
18 | validateAllTextarea(): boolean | formValidator.validateAllTextarea() | Validates all textarea fields within the form. | β
| β |
19 | validateCheckbox(checkbox: HTMLInputElement or string): boolean | formValidator.validateCheckbox('agreeCheckbox') | Validates a checkbox field with the specified ID or HTML checkbox element. | β
| β |
20 | validateAllCheckbox(): boolean | formValidator.validateAllCheckbox() | Validates all checkbox fields within the form. | β
| β |
21 | validateRadio(radioName: string): boolean | formValidator.validateRadio('genderRadio') | Validates a radio button group with the specified name. | β
| β |
22 | validateAllRadio(): boolean | formValidator.validateAllRadio() | Validates all radio button groups within the form. | β
| β |
23 | restrictInputLengthWithCounter(inputElement: HTMLInputElement, counterContainer: HTMLElement, options: Object = {}) | formValidator.restrictInputLengthWithCounter('messageField', 100) | Counts characters in the specified input field, restricts input, and displays a character counter. | β
| β |
24 | checkType(variable: any): string | formValidator.checkType('hello') | Determines the type of a given variable and returns a string representation of the type, or 'unknown' if type cannot be determined. | β
| β
|
25 | getPageUrl():string | formValidator.getPageUrl() | Returns the current page URL | β
| β |
26 | hashPassword(password):Promise | formValidator.hashPassword('1234-efrgty').then((response)=>{ console.log(response) }); | Returns the promise which has the hashed password | β
| β
|
27 | displayError(errorDetails:object):void | formValidator.displayError(errorDetails) | Displays an error message for a given period of time | β
| β |
28 | loading(message:string, submitBtn: HTM,String) | formValidator.loading("Loading...", "submitBtnId") | Displays a loading message for your button | β
| β |
29 | isOnline() | formValidator.isOnline() | Checks if your browser's online π | β
| β |
30 | reset(form?: HTMLFormElement) | formValidator.reset() | Reset form inputs and selections π | β
| β |
31 | verifyPassword(password1: string, password2: string, isHashed = false): Promise | formValidator.verifyPassword('userInputPassword', 'hashedStoredPassword', true) | Asynchronously compares two passwords, supporting both hashed and plaintext formats. Uses bcrypt.compare for hashed passwords and direct comparison for plaintext. Resolves to true if passwords match; otherwise, returns false or an error. | β
| β
|
32 | getFormDetails(HTML Element form): Object | formValidator.getFormDetails(form) | Fetches all values of the inputs with a name or data-attr-name HTML attributes on a form element like input, select, textareas, etc. | β
| β |
33 | redirect(string [url=this.getPageUrl()], [number delay=0]) | formValidator.redirect() | Redirects the user to a specified URL, either immediately or after a specified delay. If running in a browser environment, it uses window.location.href for redirection. In a non-browser environment (e.g., Node.js console), it logs a message indicating the redirection. β | β
| |
π Usage
The NFSFU234 Form Validation Library is a versatile toolbox that empowers you to validate forms, submit them, and handle AJAX requests effortlessly. Below, you'll find a breakdown of how to wield each function listed in the table above. With these tools at your disposal, you'll be equipped to create sleek and reliable form interactions. Let's dive in! π π‘
submit()
The submit
function is used to submit a form. When you call this function, you are going to be automatically validating the form and then it will process for submitting.
formValidator.submit();
validate():boolean
The validate()
function is used to validate a form. When you call this function, you are going to validating the form and will return a boolean value (true or false) to indicate if the form meets it's requirments. If it does not meet the requirements, the error messages will be displayed.
if ( formValidator.validate() )
{
console.log("Form Validation Success");
}
else
{
console.error("Form Validation Failed");
}
isEmail(email: string): boolean
The isEmail
function checks if the given email is in a valid email format and returns a boolean value.
const isValidEmail = formValidator.isEmail('example@example.com');
console.log(isValidEmail);
isURL(url: string): boolean
The isURL
function checks if the given string is a valid URL and returns a boolean value.
const isValidURL = formValidator.isURL('https://www.example.com');
console.log(isValidURL);
isZipcode(zipcode: string): boolean
The isZipcode
function checks if the given string is a valid ZIP code and returns a boolean value.
const isValidZipcode = formValidator.isZipcode('12345');
console.log(isValidZipcode);
generateRandomPassword(): string
The generateRandomPassword
function generates a random password between the length of 8 and 16 and it will return the password generated.
const randomPassword = formValidator.generateRandomPassword();
console.log(randomPassword);
checkPassword(password: string, shouldIncludeSymbol: bool): boolean
The checkPassword
function checks the strength of the provided password and returns a boolean value indicating if it meets the required criteria (e.g., minimum length, 1 small case letter, 1 capital case letter, 1 number.). It also accepts a second paramter shouldIncludeSymbol
which is of boolean
type. If the value is set to true, the function will check the password and return true if the password contains all the requirements (e.g., minimum length, 1 small case letter, 1 capital case letter, 1 number and 1 symbol)
const isStrongPassword = formValidator.checkPassword('StrongP@ssword123');
console.log(isStrongPassword);
const isStrongPassword1 = formValidator.checkPassword('StrongP@ssword123', true);
console.log(isStrongPassword1);
verifyPassword(password1: string, password2: string, isHashed = false): Promise<boolean>
The verifyPassword
function asynchronously compares two passwords, supporting both hashed and plaintext passwords. If isHashed
is true, it uses bcrypt.compare
to compare hashed passwords. If isHashed
is false, it directly compares plaintext passwords. Returns a Promise resolving to true if passwords match, and false otherwise or in case of an error.
(async () => {
try {
const isPasswordMatch = await formValidator.verifyPassword(password, password2);
console.log( isPasswordMatch);
} catch (error) {
console.error(error);
}
})();
getFormDetails(form: HTMLFormElement)
Fetches all values of the inputs with a name
or data-attr-name
HTML attributes on a form element like input, select, textareas, etc.
const myFormDetails = formValidator.getFormDetails();
console.log(myFormDetails);
const form = document.getElementById('myForm');
const myFormDetails = formValidator.getFormDetails(form);
console.log(myFormDetails);
togglePasswordVisibility(icons: Object, form: HTMLFormElement or string)
The togglePasswordVisibility
function is used to enable the password visibility toggle feature for password input fields within a given form. When called, it allows users to toggle the visibility of their password, displaying plain text or masked characters (password dots).
Parameters:
-
icons
(optional): The icons
parameter is an optional parameter that allows you to customize the icons used for showing and hiding the password. It expects an object with two properties: 'show'
and 'hide'
. You can provide any text or HTML content as the icon for showing and hiding the password. If this parameter is not provided, the default texts "show" for show and "hide" for hide will be used.
-
form
(optional): The form
parameter accepts either an HTMLFormElement or a string representing the ID of the form element that contains the password inputs. If you pass a string as the form ID, the function will search for the form element in the document using the provided ID. If the form is not found, it will use the form from the instance of the library.
Example:
<div class='input'>
<input type="password" id="passwordField" placeholder='Type Password'>
<button class="js-togglePassword">Toggle</button>
</div>
formValidator.togglePasswordVisibility({ 'show': 'ποΈ', 'hide': 'π' }, 'myForm');
ajax(AJAXOptions: Object): Promise
The ajax
function is used to make an AJAX request using the provided AJAXOptions
. It returns a Promise that will resolve to the server's response (in JSON format) or reject with an error.
Parameters:
AJAXOptions
: An object containing the following AJAX request options:
url
(required): The URL to which the AJAX request will be sent.
RequestMethod
(required): The HTTP method for the AJAX request, such as 'GET'
, 'POST'
, 'PUT'
, 'DELETE'
, etc.
RequestHeader
(required): An object representing the request headers to be included in the AJAX request.
RequestType
(optional): The response type for the AJAX request. This parameter is optional and defaults to 'json'
.
Returns:
The ajax
function returns a Promise that will resolve to the server's response (in JSON format) if the request is successful or reject with an error if there is an issue with the request.
Example:
const AJAXOptions = {
url: 'https://api.example.com/data',
RequestMethod: 'POST',
RequestHeader: {
'Content-Type': 'application/json',
},
};
formValidator.ajax(AJAXOptions)
.then((response) => {
console.log('Request successful', response);
})
.catch((error) => {
console.error('Request failed', error);
});
(async () => {
try {
const response = await formValidator.ajax(AJAXOptions);
console.log(response);
} catch (error) {
console.error(error);
}
})();
getAJAXResponse(): Promise | false
The getAJAXResponse
function is used to retrieve the response from the last AJAX request made using the ajax
function. It returns the AJAX response as a Promise if available or false if the AJAX request has been resolved.
Note: This function is primarily used when submitting a form via AJAX, and the user wants to access the response from the server database. If you wish to perform an AJAX request and want to access the server's response, you should use the ajax()
function provided by the library.
Example Usage:
formValidator.submit(formDetails, ajaxOptions);
const submitButton = document.querySelector("#submitButton");
submitButton.addEventListener('click', () => {
const ajaxResponse = formValidator.getAJAXResponse();
console.log(ajaxResponse);
});
containsOnlyIntegers(inputValue: string): boolean
The containsOnlyIntegers
function checks if the given input value contains only integers and returns a boolean value.
const isOnlyIntegers = formValidator.containsOnlyIntegers('12345');
console.log(isOnlyIntegers);
countString(inputValue: string): number
The countString
function counts the number of characters in the provided input value and returns the count.
const charCount = formValidator.countString('Hello, World!');
console.log(charCount);
validateInput(input: HTMLInputElement | string): boolean
The validateInput
function validates an input field with the specified ID or directly the HTML input element and returns a boolean value indicating if it is valid.
Parameters:
input
: Either the HTMLInputElement (input element) or the string ID of the input element to be validated.
Usage:
const usernameField = document.getElementById('usernameField');
const isValidInput = formValidator.validateInput(usernameField);
console.log(isValidInput);
OR
const isValidInput = formValidator.validateInput('usernameField');
console.log(isValidInput);
In the validateInput
function, you can pass either the HTMLInputElement (input element) directly or the string ID of the input element you want to validate. The function will return true
if the input field is valid according to the specified validation rules, otherwise false
.
validateAllInput(): boolean
The validateAllInput
function validates all input fields within the form and returns a boolean value indicating if all inputs are valid.
const areAllInputsValid = formValidator.validateAllInput();
console.log(areAllInputsValid);
validateSelect(select: HTMLSelectElement | string): boolean
The validateSelect
function validates a select field with the specified ID or directly the HTML select element and returns a boolean value indicating if it is valid.
Parameters:
select
: Either the HTMLSelectElement (select element) or the string ID of the select element to be validated.
Usage:
const countrySelect = document.getElementById('countrySelect');
const isValidSelect = formValidator.validateSelect(countrySelect);
console.log(isValidSelect);
OR
const isValidSelect = formValidator.validateSelect('countrySelect');
console.log(isValidSelect);
validateAllSelect(): boolean
The validateAllSelect
function validates all select fields within the form and returns a boolean value indicating if all selects are valid.
const areAllSelectsValid = formValidator.validateAllSelect();
console.log(areAllSelectsValid);
validateTextarea(textarea: HTMLTextAreaElement | string): boolean
The validateTextarea
function validates a textarea field with the specified ID or directly the HTML textarea element and returns a boolean value indicating if it is valid.
Parameters:
textarea
: Either the HTMLTextAreaElement (textarea element) or the string ID of the textarea element to be validated.
Usage:
const messageTextarea = document.getElementById('messageTextarea');
const isValidTextarea = formValidator.validateTextarea(messageTextarea);
console.log(isValidTextarea);
OR
const isValidTextarea = formValidator.validateTextarea('messageTextarea');
console.log(isValidTextarea);
validateAllTextarea(): boolean
The validateAllTextarea
function validates all textarea fields within the form and returns a boolean value indicating if all textareas are valid.
const areAllTextareasValid = formValidator.validateAllTextarea();
console.log(areAllTextareasValid);
validateCheckbox(checkbox: HTMLInputElement | string): boolean
The validateCheckbox
function validates a checkbox field with the specified ID or directly the HTML checkbox element and returns a boolean value indicating if it is valid.
Parameters:
checkbox
: Either the HTMLInputElement (checkbox element) or the string ID of the checkbox element to be validated.
Usage:
const agreeCheckbox = document.getElementById('agreeCheckbox');
const isValidCheckbox = formValidator.validateCheckbox(agreeCheckbox);
console.log(isValidCheckbox);
OR
const isValidCheckbox = formValidator.validateCheckbox('agreeCheckbox');
console.log(isValidCheckbox);
validateAllCheckbox(): boolean
The validateAllCheckbox
function validates all checkbox fields within the form and returns a boolean value indicating if all checkboxes are valid.
const areAllCheckboxesValid = formValidator.validateAllCheckbox();
console.log(areAllCheckboxesValid);
validateRadio(radioName: string): boolean
The validateRadio
function validates a radio button group with the specified name and returns a boolean value indicating if it is valid.
Parameters:
radioName
: The name attribute of the radio button group to be validated.
Usage:
HTML:
<div>
<input type="radio" name="genderRadio" value="male" required> Male
</div>
<div>
<input type="radio" name="genderRadio" value="female"> Female
</div>
JavaScript:
const isValidRadio = formValidator.validateRadio('genderRadio');
console.log(isValidRadio);
validateAllRadio(): boolean
The validateAllRadio
function validates all radio button groups within the form and returns a boolean value indicating if all radios are valid.
const areAllRadiosValid = formValidator.validateAllRadio();
console.log(areAllRadiosValid);
restrictInputLengthWithCounter(inputElement: HTMLInputElement, counterContainer: HTMLElement, options: Object = {})
The restrictInputLengthWithCounter
function is used to count the characters in the specified input field and restrict the input based on the provided options. Additionally, it displays a character counter using the given counterContainer
element.
Parameters:
inputElement
: The HTMLInputElement for which the character count and input restriction are applied.
counterContainer
: The HTMLElement representing the container to display the character counter. If not provided, a new div
element with the class 'js-counterContainer' will be created and appended next to the input element.
options
(optional): An object containing additional configuration options for the feature. The available options are:
maxLength
(default: 250): The maximum allowed length for the input field.
minLength
(default: 0): The minimum required length for the input field.
shouldButtonDisable
(default: false): A boolean indicating whether to disable the form submit button based on input validity.
formId
(default: null): The ID of the form associated with the input. If not provided, the function will try to find the form element automatically.
Usage:
<input type="text" id="messageField">
<span class="js-counterContainer"></span>
const inputElement = document.getElementById('messageField');
const counterContainer = document.querySelector('.js-counterContainer');
formValidator.restrictInputLengthWithCounter(inputElement);
const options = {
maxLength: 150,
minLength: 10,
shouldButtonDisable: true,
formId: 'myForm'
};
formValidator.restrictInputLengthWithCounter(inputElement, counterContainer, options);
getPageUrl():string
The getPageUrl()
function is a utility designed if you need to get the URL of the current page you are in.
Usage
const url = formValidator();
console.log(url);
checkType(variable: any): string
The checkType
function is a utility designed to determine the type of a given variable. It assists in identifying whether a variable is a string, number, boolean, object, function, or other data type. This function returns a string representing the type of the variable, or 'unknown'
if the type cannot be determined.
Usage
const variable = "Hello, world!";
const type = formValidator.checkType(variable);
console.log(`The type of the variable is: ${type}`);
Parameters
variable
(any
): The variable for which you want to determine the type.
Return
string
: A string representing the type of the variable, e.g., 'string'
, 'number'
, 'object'
, 'function'
, etc. If the type cannot be determined, 'unknown'
is returned.
Example
const variable = { key: "value" };
const type = formValidator.checkType(variable);
const variable = 42;
const type = formValidator.checkType(variable);
const variable = () => { console.log("Hello, world!"); };
const type = formValidator.checkType(variable);
hashPassword(password):Promise
The formValidator.hashPassword()
function is a function tht is used to hash a password or string. It uses the ByCrypt Library to has the string passed.
Usage
formValidator.hashPassword('@Password123')
.then( hashedPassword =>{
console.log(hashedPassword);
})
.catch( (error)=>{
console.error(error);
} );
displayError(errorDetails):void
The displayError()
function is used to display an error. The error can either be inline or modal. This function takes up 1 parameter and it is an object. Find below the paramters required
Parameters:
errorDetails
: An object containing the following error details options:
type
(required): The type of error message container you would like to use. You have 2 options either inline
or modal
.
message
(required): The message that is to be displayed.
duration
(required): The duration for the message to be shown
element
(required): This is a HTML Element where the error container will be passed to. It can be an input or textarea element or probally a section or div element, whichever meets the requirements for the error you want to display.
success
(optional): You are indicating if this is a success or failure message. If not set, the default of failure
will be used.
Usage
const form = document.getElementById('form');
const errorDetails = {
type : 'modal',
message: 'Hello Worldπ',
duration: 3000,
element: form,
success: false,
}
formValidator.displayError(errorDetails);
Example
Assumming you make a request to an API and you will need to display the response message to the user, the perfect way to that is to use the ajax()
function thereafter you can use the displayError()
function and in your type attribute, it is most preffered to use modal
type. Assuming the response has a status and message attribute on response. Let's take a look at how this works.
const form = document.getElementById('form');
const AJAXOptions = {
url: 'https://api.example.com/data',
RequestMethod: 'GET',
RequestHeader: {
'Content-Type': 'application/json',
},
};
formValidator.ajax(AJAXOptions)
.then((response) => {
console.log('Request successful', response);
const status = response.status;
const message = response.message;
let errorDetails;
if ( status != 200 )
{
errorDetails = {
type : 'modal',
message: message,
duration: 3000,
element: form,
success: false,
}
}
else
{
errorDetails = {
type : 'modal',
message: message,
duration: 3000,
element: form,
success: true,
}
}
formValidator.displayError(errorDetails);
})
.catch((error) => {
console.error('Request failed', error);
});
loading(message, submitBtn = null):bool
The loading()
function is used to display a loading message in your button. This function is ideal if you choose to use the validate() function independly. Because you might wish for the users to know they are awaiting a response, so you can have a little message or animation you wish to show between validation and perhaps awaiting the results from the AJAX request.
Parameters:
message
: This will contain the message or HTML contents you wish to insert into your Button or set as the value of the button.
submitBtn (optional)
: This is optional because assuming you have initialized the NFSFU234FormValidation Library, you would have had an inital form so the button or submit button found in the form will be used else you want a diffrent button, you can either pass the HTML Element or pass the ID of the button
Usage
formValidator.loading('Loading Message');
const button = document.getElementById('btnId');
formValidator.loading('Loading Message', button);
isOnline(): boolean
The isOnline
function checks if the current environment is a browser and determines whether the browser is online. It does this by examining the navigator.onLine
property, which indicates the online status of the browser. This function is useful when you need to verify the browser's connectivity status before making network requests or performing actions that depend on internet access.
The function returns a boolean value, true
if the browser is online and false
if it's not.
const isBrowserOnline = formValidator.isOnline();
console.log(isBrowserOnline);
reset(form?: HTMLFormElement): boolean
The reset
function provides a convenient way to reset form elements within a given HTML form or the internal form of a validation tool. It resets input fields, textareas, selects, radios, and checkboxes to their default values or empty states, ensuring that the form is in a clean state.
You can optionally pass a form
parameter to specify a different form to reset; otherwise, it will operate on the internal form. This function can be particularly helpful when you want to clear user inputs and start fresh after a form submission or user interaction.
The function returns a boolean value, true
if the reset operation is successful, and false
if any issues occur during the reset process.
const isResetSuccessful = formValidator.reset();
console.log(isResetSuccessful);
redirect(string [url=this.getPageUrl()], [number delay=0])
The redirect
function redirects the user to a specified URL, either immediately or after a specified delay. If running in a browser environment, it utilizes window.location.href
for redirection. In a non-browser environment (e.g., Node.js console), it logs a message indicating the redirection.
formValidator.redirect("https://example.com", 3);
This function takes an optional url
parameter, defaulting to the current page's URL if not provided, and an optional delay
parameter, defaulting to 0 seconds.
Using NFSF234 Form Validation Library in Node.js Application
To use NFSF234 Form Validation Library in your Node Js Application, follow the steps below:
Import the library in your Node.js script:
const NFSFU234FormValidation = require('nfsfu234-form-validation');
Initialize an instance of the library and use its functions:
const formValidator = new NFSFU234FormValidation();
const isValidEmail = formValidator.isEmail('example@example.com');
console.log('Is Valid Email:', isValidEmail);
const isValidURL = formValidator.isURL('https://www.example.com');
console.log('Is Valid URL:', isValidURL);
For more functions you can use in your Node.js
application, kindly vist the Node.js Column in the Available Functions in NFSFU234 Form Validation Library Table
License π
NFSFU234 Form Validation - Your Go-To for Simple, Flexible, and Powerful Form Validation Library.
Licensed under the MIT License.
For further insights, dive into the LICENSE.
Contributing ππ
Join the Journey! ππ
As I embark on my maiden voyage into the world of open-source libraries, I find myself pioneering this path solo. However, I'm extending a heartfelt invitation to you to be a part of something exciting. Your contribution could be the spark that ignites remarkable outcomes.
Intrigued? Ready to dive into this coding adventure? Don't hesitate to reach out by opening issues or pull requests in the GitHub repository. Your input, even in this seemingly individual endeavor, holds boundless value.
Contribute and Elevate: Join hands with me as we learn, grow, and raise the bar for the NFSFU234 Form Validation library! ππ€
For more details about how to contribute, check out the CONTRIBUTING.md file. Your collaborative spirit is greatly appreciated. Together, we can achieve great things!
Credits π
NFSFU234 Form Validation was brought to life with care by yours truly, NFORSHIFU234 Dev ππ₯ β also known as Shifu-Nfor Nyuiring-yoh Rhagninyui. It's a special journey as my first-ever library creation! ππΆ
Your trust and support mean the world to me. Together, let's make the web a more validated and user-friendly place! πβ¨
Support π€
If you have any queries, questions, or simply need assistance, don't hesitate to reach out at nf.validator234@gmail.com
. You can also connect on social media @nf_validator234
. I'm here to help and ensure your experience with NFSFU234 Form Validation is as smooth as possible! π¬π§
Congratulations! You've successfully integrated NFSFU234 Form Validation into your project, enhancing your ability to validate form inputs and deliver exceptional user experiences.
Armed with this knowledge, you're all set to proficiently initialize and employ the NFSFU234 Form Validation Library within your projects. Happy coding! ππ¨βπ»