Sitemap

How to Effortlessly Validate Usernames in React Native (The Right Way) | Part 1

2 min readAug 4, 2024

--

Introduction

User input validation is a crucial aspect of developing mobile applications. It ensures data integrity and improves user experience by providing immediate feedback. In this blog post, we’ll discuss a simple yet effective way to validate user names in a React Native application using JavaScript.

The Problem

When building forms that collect user data, such as sign-up or profile update forms, it’s important to ensure that the names entered by users do not contain any special characters. Special characters can cause issues with data storage, processing, and display.

The Solution

We’ll use a small JavaScript function to strip out any unwanted special characters from user names. This function will replace any character that is not a letter or a number with an empty string, effectively removing it from the input.

Define Rules Clearly

Allow only:

  • Letters (a–z, A–Z)
  • Numbers (0–9)
  • Optional underscore (_) and/or period (.) if needed
const usernameRegex = /^[a-zA-Z0–9._]{3,20}$/;

The Code

Here’s the code for the validateName function:

export const validateName = (value: string) => {
const name = value.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
return name;
};

Real-time Validation with Feedback

const validateUsername = (username) => {
return usernameRegex.test(username);
};
// Usage
<TextInput
value={username}
onChangeText={(text) => {
setUsername(text);
setIsValid(validateUsername(text));
}}
placeholder="Enter username"
/>
{!isValid && <Text style={{ color: 'red' }}>Invalid username format</Text>}
// App.js
import React, { useState } from 'react';
import { SafeAreaView, StyleSheet, Text, TextInput, View } from 'react-native';
import { validateName } from './validators';

const App = () => {
const [name, setName] = useState('');
const [validatedName, setValidatedName] = useState('');

const handleNameChange = (value: string) => {
setName(value);
setValidatedName(validateName(value));
};

return (
<SafeAreaView style={styles.container}>
<Text style={styles.title}>Name Validation Example</Text>
<TextInput
style={styles.input}
placeholder="Enter your name"
value={name}
onChangeText={handleNameChange}
/>
<View style={styles.outputContainer}>
<Text style={styles.label}>Validated Name:</Text>
<Text style={styles.output}>{validatedName}</Text>
</View>
</SafeAreaView>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 16,
},
title: {
fontSize: 24,
marginBottom: 16,
},
input: {
width: '100%',
height: 40,
borderColor: 'gray',
borderWidth: 1,
paddingHorizontal: 8,
marginBottom: 16,
},
outputContainer: {
alignItems: 'center',
},
label: {
fontSize: 18,
},
output: {
fontSize: 18,
fontWeight: 'bold',
color: 'blue',
},
});

export default App;

--

--

Hemanth KV
Hemanth KV

Written by Hemanth KV

Senior Software Engineer @Dbiz.ai | React, React Native, Next.js, Python | Support my work: https://www.buymeacoffee.com/infoappmakk

No responses yet